/**
 * Created by huotaol on 2017/9/21.
 */
import React from "react";
import {Button, Icon, Input, InputNumber, message, Modal, Popconfirm, Table, Tooltip, Upload} from "antd";
import request, {get} from "@/axios/tools";
import {connect} from "react-redux";
import {updateMenu} from "@/action";
// const Option = Select.Option;
// const CheckboxGroup = Checkbox.Group;
const previewFile = (file, callback) => {
    const reader = new FileReader();
    reader.onloadend = () => callback(reader.result);
    reader.readAsDataURL(file);
};


class ModifyRestaurant extends React.Component {

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            name: '',
            address: '',
            discount: 100,
            phones: [''],
            inputPhone: '',
            foodTypeList: [],
            // 菜单编辑 modal 控制
            visible: false,
            // 饭馆信息 modal 控制
            editVisible: false,
            foodName: '',
            foodDescription: '',
            previousState: {},
            basePicUrl: '',
            editType: ''
        };
    }

    componentDidMount() {
        const {updateMenu} = this.props
        this._requestData();
        this._requestMenus();
    }

    //查询饭店信息
    _requestData = () => {
        get('/restaurant/restaurant/' + this.props.auth.data.restaurant).then(data => {
            this.setState({...data, phones: data.phones ? data.phones.split(',') : ['']});
        });
    };

    //查询该饭店菜单信息
    _requestMenus() {
        get('/restaurant/listMenus/' + this.props.auth.data.restaurant).then(data => {
            data.list.map((item, index) => {
                return item.key = item.id
            })
            this.setState({foodTypeList: data.list, basePicUrl: data.basePicUrl});
        });
    };

    //上传饭店信息
    _postData = () => {
        const userID = this.props.auth.data.user.id;
        const {id = 0, name, address, phones} = this.state;
        request({
            url: '/restaurant/restaurant', method: 'post', params: {
                userID,
                id,
                name,
                address,
                phones: phones.join(',')
            }
        })
    };

    _deleteMenu = menuID => {
        if (menuID) {
            return request({url: `/restaurant/foodMenu/${menuID}`, method: 'delete'})
        }
    };
    handlerEditinfo = () => {
        this.setState({
            previousState: {
                ...this.state,
                phones: this.state.phones.slice()
            },
            editVisible: true
        });
    }
    onEditMenu = (id, record) => {
        const {foodTypeList, basePicUrl} = this.state
        const {name, description} = foodTypeList.filter((item) => {
            return item.id === id
        })[0]
        const {fileData} = record;
        let fileList = [];
        if (fileData) {
            fileData.uid = id;
            fileData.url = basePicUrl + '/' + fileData.local;
            fileData.status = 'done';
            fileList.push(fileData);
        }

        this.props.updateMenu({
            ...this.props.menuState,
            name,
            description,
            id,
            fileList
        })
        this.setState({
            visible: true,
            editType: 'edit'
        });
    }
    removePhones = (index) => {
        let {phones} = this.state
        phones.splice(index, 1)
        this.setState({phones})
    }

    render() {
        const phones = this.state.phones;
        const columns = [
            {
                title: '图片',
                dataIndex: 'fileData',
                width: 100,
                render: text => {
                    return (
                        <div style={{backgroundColor: '#eee', textAlign: 'center'}}>
                            <img src={text ? this.state.basePicUrl + '/' + text.local : ''}/>
                        </div>
                    )
                }
            }, {
                title: 'ID',
                dataIndex: 'id',
            }, {
                title: '名称',
                dataIndex: 'name',
                render: text => <a href="#">{text}</a>,
            }, {
                title: '描述',
                dataIndex: 'description',
            }, {
                title: '操作',
                key: 'action',
                width: 220,
                render: (text, record) => (
                    <span>
                    <Button onClick={() => this.onEditMenu(record.id, record)}>编辑</Button>
                    <span className="ant-divider"/>
                    <Popconfirm title="确定删除?" onConfirm={() => {
                        this._deleteMenu(record.id).then(data => {
                            const {foodTypeList} = this.state;
                            foodTypeList.splice(foodTypeList.indexOf(record), 1);
                            this.setState({foodTypeList});
                        });
                    }}>
                        <Button>删除</Button>
                    </Popconfirm>
                        {/* <span className="ant-divider"/> */}
                </span>
                ),
            }];
        const phoneInput = phones.map((item, index) => {
            return (
                <div className="phone-field" key={index}>
                    <Input placeholder="请输入联系电话" value={phones[index] }
                           onChange={e => {
                               phones[index] = e.target.value
                               this.setState({phones});
                           }}
                           style={{width: '90%'}}/>
                    <span style={{display: 'inline-block', width: '10%', textAlign: 'center'}}>
                        <Icon
                            className="dynamic-delete-button"
                            type="minus-circle-o"
                            style={{fontSize: 15, color: '#ff5d65'}}
                            onClick={() => this.removePhones(index)}
                        />
                    </span>
                </div>
            )
        })
        let phonesStr = phones.filter((item) => {
            return item != '';
        })
        phonesStr = phonesStr.join(', ');
        return (
            <div className="clearfix">
                <div className="content-container">
                    <h3 className="pannel-title">
                        饭店信息
                        {
                            this.state.name ?
                                <Tooltip placement="top" title={'编辑饭店信息'}>
                                    <span className="edit-btn" onClick={() => {
                                        this.handlerEditinfo()
                                    }}>
                                        <Icon type="edit"/>
                                    </span>
                                </Tooltip> : ''
                        }
                    </h3>
                    <div className="info-pannel">
                        <div className="info-item">
                            <span className="info-label"><Icon type="shop"/></span>
                            <span className="info-value">
                                {this.state.name}
                            </span>
                        </div>
                        <div className="info-item">
                            <span className="info-label"><Icon type="environment-o"/></span>
                            <span className="info-value">
                                {this.state.address}
                            </span>
                        </div>
                        <div className="info-item">
                            <span className="info-label">
                                {
                                    this.state.discount ? <Icon type="tag-o"/> : ''
                                }
                            </span>
                            <span className="info-value">
                                {this.state.discount && this.state.discount + '%'}
                            </span>
                        </div>
                        <div className="info-item">
                            { phonesStr.trim().length ?
                                <span className="info-label">
                                    <Icon type="phone"/>
                                </span> : ''
                            }
                            <span className="info-value">
                                { phonesStr }
                                {/* {phones && phones.map((item, index) => {
                                 if (index < phones.length-1) {
                                 item = item + ','
                                 }
                                 return item
                                 })} */}
                            </span>
                        </div>
                    </div>

                </div>
                <div className="content-container">
                    <h3 className="pannel-title">菜单列表</h3>
                    <div className="opt-box">
                        <Button type="default" onClick={() => {
                            this.setState({visible: true, editType: 'add'});
                            // 新增菜单时 清空菜单值
                            this.props.updateMenu({})
                        }}>添加</Button>
                    </div>
                    <Table columns={columns} size="middle" dataSource={this.state.foodTypeList}/>
                </div>

                <Modal
                    title="添加菜单"
                    visible={this.state.visible}
                    onOk={e => {
                        this.setState({visible: false});
                    }}
                    onCancel={e => {
                        this.setState({visible: false});
                    }}
                    footer={null}
                >
                    {/* this.props.auth.data.restaurant */}
                    <FoodMenu {...this.props}
                              ref="foodMenu"
                              name={this.state.foodName}
                              description={this.state.foodDescription}
                              restaurantID={this.props.auth.data.restaurant}
                              fileData={this.state.fileData}
                              editType={this.state.editType}
                              success={() => {
                                  this.setState({visible: false});
                                  this._requestMenus();
                              }}/>
                </Modal>
                <Modal
                    title="饭店信息"
                    visible={this.state.editVisible}
                    onOk={e => {
                        this.setState({editVisible: false});
                        this._postData();
                    }}
                    onCancel={e => {
                        this.setState({
                            ...this.state.previousState,
                            editVisible: false
                        });
                    }}
                >

                    <label className="edit-label">饭馆名称:</label>
                    <div className="edit-field">
                        <Input placeholder="请输入饭店名字" value={this.state.name} onChange={e => {
                            this.setState({name: e.target.value});
                        }}/>
                    </div>

                    <div className="space-bar"></div>
                    <label className="edit-label">饭馆名称:</label>
                    <div className="edit-field">
                        <Input placeholder="请输入饭店地址" value={this.state.address} onChange={e => {
                            this.setState({address: e.target.value});
                        }}/>
                    </div>
                    <div className="space-bar"></div>
                    <label className="edit-label">联系电话:</label>
                    {/* <div>
                     {phones && phones.map(item => <Tag closable onClose={value => {
                     phones.splice(phones.indexOf(item), 1);
                     this.setState({phones});
                     }}>{item}</Tag>)}
                     </div> */}
                    <div className="edit-field">
                        {/* <Input placeholder="请输入联系电话" value={this.state.inputPhone} onChange={e => {
                         this.setState({inputPhone: e.target.value});
                         }}/> */}
                        {phoneInput}
                    </div>
                    {/* <div className="space-bar"></div> */}
                    <label className="edit-label"></label>
                    <div className="edit-field">
                        <Button type="dashed" style={{width: '200px'}} onClick={() => {
                            phones.push('');
                            this.setState({phones})
                            {/* let item = this.state.inputPhone;
                             if (item) {
                             phones.push(item);
                             this.setState({phones, inputPhone: ''});
                             } */
                            }
                        }}><Icon type="plus"/>添加</Button>
                    </div>
                    <div className="space-bar"></div>
                    <label className="edit-label">饭馆折扣:</label>
                    <div className="edit-field">
                        <InputNumber min={0} max={100}
                                     defaultValue={100}
                                     value={this.state.discount}
                                     onChange={value => {
                                         this.setState({discount: value});
                                     }}
                                     formatter={value => `${value}%`}
                                     parser={value => value.replace('%', '')}/>
                    </div>
                </Modal>
            </div>
        );
    }
}

class FoodMenu extends React.Component {

    static propTypes = {
        // success: React.PropTypes.function,
        id: React.PropTypes.number,
        name: React.PropTypes.string,
        description: React.PropTypes.string,
        restaurantID: React.PropTypes.number,
    };

    _postMenu = () => {
        const id = this.props.id || this.props.menuState.id || 0;
        const {name, description, fileList} = this.props.menuState;
        const {editType} = this.props;
        if (name) {
            request({
                url: '/restaurant/foodMenu/' + this.props.restaurantID, method: 'post', params: {
                    id: id,
                    name: name,
                    description: description
                }
            }).then(data => {
                /**
                 * 重置菜单状态
                 */
                this.props.updateMenu({
                    name: '',
                    description: ''
                })
                this.setState({
                    loading: false,
                });
                if (!fileList[0] || fileList[0].local) {
                    this.props.success();
                }
            }).catch(e => {
                message.warn('上传失败');
                this.setState({loading: false});
            });
        } else {
            message.warn('参数错误');
            this.setState({loading: false});
        }
    };

    _uploadImage = () => {
        const id = this.props.id || this.props.menuState.id || 0;
        if (id && this.props.editType === 'edit') {
            const {fileList} = this.props.menuState;
            if (fileList[0] && fileList[0].local) {
                return
            }
            // console.log(fileList[0])
            let params = {id, file: fileList[0]};

            request({url: '/restaurant/foodMenuPic', method: 'post', params}).then((res) => {
                console.log(res);
                this.props.updateMenu({...this.props.menuState, fileList: []});
                this.props.success();
            }, (err) => {
                message.error('图片上传失败');
                console.log(err)
            })
        }
    };

    /**
     * 输入时更新菜单（单一字段）状态
     */
    updateValue = (key, value) => {
        this.props.updateMenu({
            ...this.props.menuState,
            [key]: value
        })
    }

    handleChange = ({fileList, file}) => {
        fileList.forEach((fileItem) => {
            previewFile(fileItem, (previewDataUrl) => {
                fileItem.url = previewDataUrl;
                this.forceUpdate();
            })
        })
        this.props.updateMenu({...this.props.menuState, fileList})
    };

    beforeUpload = () => {
        return false;
    }

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            name: props.name,
            description: props.description,
            loading: false,
            fileList: props.fileList
        };
        console.log(this.props)
    }

    uploadButton = () => (
        <div>
            <Icon type="plus"/>
            <div className="ant-upload-text">Upload</div>
        </div>
    );

    render() {
        const id = this.props.id || this.props.menuState.id || 0;
        return (
            <div>
                <Input placeholder='请输入名称' value={this.props.menuState.name} onChange={e => {
                    this.updateValue('name', e.target.value)
                    {/* this.setState({name: e.target.value}); */
                    }
                }}/>
                <div style={{marginTop: '15px'}}></div>
                <Input.TextArea placeholder='请输入描述' autosize={true} value={this.props.menuState.description}
                                onChange={e => {
                                    this.updateValue('description', e.target.value)
                                    {/* this.setState({description: e.target.value}); */
                                    }
                                }}/>
                <div style={{marginTop: '15px'}}></div>
                {
                    id !== 0 && (
                        <div className="picture-upload-box clearfix" style={{minHeight: '100px'}}>
                            <Upload
                                listType="picture-card"
                                beforeUpload={this.beforeUpload}
                                fileList={this.props.menuState.fileList}
                                onChange={this.handleChange}
                            >
                                {this.props.menuState.fileList.length < 1 && this.uploadButton()}
                            </Upload>
                            <div style={{marginTop: '5px'}}></div>
                        </div>
                    )
                }

                <Button key="submit" type="primary" size="large" loading={this.state.loading} onClick={e => {
                    this.setState({loading: true});
                    this._postMenu();
                    this._uploadImage();
                }}>
                    保存
                </Button>
            </div>
        );
    }

    // componentDidMount () {
    //     console.log(this.props)
    // }
}

const mapStateToProps = state => {
    const {auth = {data: {}}} = state.httpData;
    const {menuState} = state
    return {auth, menuState};
};
const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        updateMenu: (...args) => dispatch(updateMenu(...args))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ModifyRestaurant);